package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.*;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.service.HResourceRelationService;
import com.flea.hclv.service.HSubmitAccountService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgRoleMapper;
import com.flea.system.entity.OrgDept;
import com.flea.system.entity.OrgRole;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.service.IFileuploadChunkService;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @program: project
 * @description: 报销单
 * @author: shiliqiang
 * @create: 2019-01-03 16:17
 * @version: 1.0
 */
@Service
public class HSubmitAccountServiceImpl implements HSubmitAccountService {

    @Autowired
    private HSubmitAccountMapper hSubmitAccountMapper;
    @Autowired
    private HResourceRelationService hResourceRelationService;
    @Autowired
    private HTravelGroupMapper hTravelGroupMapper;
    @Autowired
    private HTimeTableMapper hTimeTableMapper;
    @Autowired
    private HProductMapper hProductMapper;
    @Autowired
    private HLineMapper hLineMapper;
    @Autowired
    private OrgRoleMapper orgRoleMapper;
    @Autowired
    private HGuideTravelGroupMapper hGuideTravelGroupMapper;

    @Override
    public ServerResponse<HSubmitAccount> selectByTravelGroupIdAndPayDeptId(String travelGroupId, String payDeptId) {
        if (StringUtils.isBlank(travelGroupId)){
            return ServerResponse.createByErrorMessage("团ID不能为空");
        }
        if (StringUtils.isBlank(payDeptId)){
            return ServerResponse.createByErrorMessage("支付部门ID不能为空");
        }
        //获取导游的工资
        HGuideTravelGroup hGuideTravelGroup = hGuideTravelGroupMapper.selectByTravelGroupId(travelGroupId);
        if (hGuideTravelGroup==null){
            return ServerResponse.createByErrorMessage("没有找到该团的导游支付信息");
        }

        HSubmitAccount account = hSubmitAccountMapper.selectByTravelGroupIdAndPayDeptId(travelGroupId,payDeptId);
        if (account==null){
            return ServerResponse.createByErrorMessage("没有找到报账单");
        }
        account.setGuideCost(hGuideTravelGroup.getPayMoney());
        return ServerResponse.createBySuccess(account);
    }

    @Override
    public ServerResponse<HLine> selectLineByTravelGroupId(String travelGroupId) {
        ServerResponse<HLine> data = this.getLine(travelGroupId);
        if (!data.isSuccess()) {
            return data;
        }
        HLine hLine = data.getData();
        return ServerResponse.createBySuccess(hLine);
    }

    @Override
    public ServerResponse<FleaPage<HSubmitAccount>> selectByDeptId(String deptUuid, int curPage, int pageSize) {
        RowBounds rowBounds = new RowBounds(curPage, pageSize);
        List<HSubmitAccount> hSubmitAccounts = hSubmitAccountMapper.selectByDeptId(deptUuid, rowBounds);
        FleaPage<HSubmitAccount> fleaPage = new FleaPage<>(hSubmitAccounts);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<Map<String, Object>> selectById(String submitAccountId) {
        HSubmitAccount entity = hSubmitAccountMapper.selectByPrimaryKey(submitAccountId);
        if (entity == null) {
            return ServerResponse.createBySuccessMessage("0");
        }
        String lineId = entity.getLineId();
        if (StringUtils.isBlank(lineId)) {
            return ServerResponse.createByErrorMessage("线路Id为空");
        }
        HLine hLine = hLineMapper.selectByPrimaryKey(lineId);
        if (hLine == null) {
            return ServerResponse.createByErrorMessage("线路不存在");
        }
        entity.setLineName(hLine.getName());
        List<HResourceRelation> files = hResourceRelationService.findFilePathByUuid(entity.getId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("submitAccount", entity);
        map.put("images", files);
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse<FleaPage<HSubmitAccount>> selectByCreateUser(String userId, int curPage, int page) {
        RowBounds rowBounds = new RowBounds(curPage, page);
        List<HSubmitAccount> list = hSubmitAccountMapper.selectByCreateId(userId, rowBounds);
        FleaPage<HSubmitAccount> fleaPage = new FleaPage<>(list);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<HSubmitAccount> selectEntityByGroupId(String groupId) {
        HSubmitAccount entity = hSubmitAccountMapper.selectByGroupId(groupId);
        if (entity == null) {
            return ServerResponse.createByErrorMessage("报账单不存在");
        }
        return ServerResponse.createBySuccess(entity);
    }

    @Override
    public ServerResponse<Map<String, Object>> selectByGroupId(String groupId) {
        HSubmitAccount entity = hSubmitAccountMapper.selectByGroupId(groupId);
        if (entity == null) {
            return ServerResponse.createBySuccessMessage("0");
        }
//        String lineId = entity.getLineId();
//        if (StringUtils.isBlank(lineId)) {
//            return ServerResponse.createByErrorMessage("线路Id为空.");
//        }
//        HLine hLine = hLineMapper.selectByPrimaryKey(lineId);
//        if (hLine == null) {
//            return ServerResponse.createByErrorMessage("线路不存在");
//        }
//        entity.setLineName(hLine.getName());
        List<HResourceRelation> files = hResourceRelationService.findFilePathByUuid(entity.getId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("submitAccount", entity);
        map.put("images", files);
        return ServerResponse.createBySuccess(map);
    }
  @Override
  public HSubmitAccount findByGroupId(String groupId) {
      return hSubmitAccountMapper.selectByGroupId(groupId);
  }
    //获取线路名称
    private ServerResponse<HLine> getLine(String groupId) {
        HTravelGroup travelGroup = hTravelGroupMapper.selectByPrimaryKey(groupId);
        if (travelGroup == null) {
            return ServerResponse.createByErrorMessage("团不存在");
        }
        String timeTableId = travelGroup.getTimeTableId();
        if (StringUtils.isBlank(timeTableId)) {
            return ServerResponse.createByErrorMessage("班期ID不能空");
        }
        HTimeTable hTimeTable = hTimeTableMapper.selectByPrimaryKey(timeTableId);
        if (hTimeTable == null) {
            return ServerResponse.createByErrorMessage("班期不存在");
        }
        String productId = hTimeTable.getProductId();
        if (StringUtils.isBlank(productId)) {
            return ServerResponse.createByErrorMessage("产品ID不能为空");
        }
        HProduct hProduct = hProductMapper.selectByPrimaryKey(productId);
        if (hProduct == null) {
            return ServerResponse.createByErrorMessage("产品不存在");
        }
        String lineId = hProduct.getLineId();
        if (StringUtils.isBlank(lineId)) {
            return ServerResponse.createByErrorMessage("线路ID不能为空");
        }
        HLine hLine = hLineMapper.selectByPrimaryKey(lineId);
        if (hLine == null) {
            return ServerResponse.createByErrorMessage("线路不存在");
        }
        return ServerResponse.createBySuccess(hLine);
    }


    @Override
    public ServerResponse<HLine> save(String userId, String model) {
        OrgDept currentUserDept = FleaOrgUtils.getCurrentUserDept(userId);
        if (currentUserDept == null) {
            return ServerResponse.createByErrorMessage("部门不能空");
        }

        JSONObject jsonObject = JSON.parseObject(model);
        HSubmitAccount entity = JSON.parseObject(model, HSubmitAccount.class);
        String travelGroupId = entity.getTravelGroupId();
        if (StringUtils.isBlank(travelGroupId)) {
            return ServerResponse.createByErrorMessage("团ID为空");
        }
        //判断团状态
        HTravelGroup hTravelGroup = hTravelGroupMapper.selectByPrimaryKey(travelGroupId);
        if (StringUtils.isBlank(travelGroupId)) {
            return ServerResponse.createByErrorMessage("团不存在");
        }
        String groupStatus = hTravelGroup.getStatus();
        if (!HConstant.HCLV_VISITOR_GROUP_ISCLOSE.equals(groupStatus) && !HConstant.HCLV_VISITOR_GROUP_ISREBACK.equals(groupStatus)){
            return ServerResponse.createByErrorMessage("团状态为回团、关闭团才可以报账");
        }
        //判断报账单是否存在
        HSubmitAccount hSubmitAccount = hSubmitAccountMapper.selectByGroupId(travelGroupId);
        if (hSubmitAccount != null) {
            return ServerResponse.createByErrorMessage("该团报账单已存在");
        }
        //获取线路名称
        ServerResponse<HLine> data = this.getLine(travelGroupId);
        if (!data.isSuccess()) {
            return data;
        }
        HLine hLine = data.getData();

        //计算费用
        Integer adultNum = entity.getAdultNum();
        Float adultTicketPrice = entity.getAdultTicketPrice();
        if (adultNum == null || adultTicketPrice == null) {
            adultNum = 0;
            adultTicketPrice = 0f;
        }
        Integer childNum = entity.getChildNum();
        Float childTicketPrice = entity.getChildTicketPrice();
        if (childNum == null || childTicketPrice == null) {
            childNum = 0;
            childTicketPrice = 0f;
        }
        Integer oldNum = entity.getOldNum();
        Float oldTicketPrice = entity.getOldTicketPrice();
        if (oldNum == null || oldTicketPrice == null) {
            oldNum = 0;
            oldTicketPrice = 0f;
        }
        Integer stuNum = entity.getStuNum();
        Float stuTicketPrice = entity.getStuTicketPrice();
        if (stuNum == null || stuTicketPrice == null) {
            stuNum = 0;
            stuTicketPrice = 0f;
        }
        Integer otherNum = entity.getOtherNum();
        Float otherTicketPrice = entity.getOtherTicketPrice();
        if (otherNum == null || otherTicketPrice == null) {
            otherNum = 0;
            otherTicketPrice = 0f;
        }
        Float groupMoney = entity.getGroupMoney();
        if (groupMoney == null) {
            return ServerResponse.createByErrorMessage("所带团费不能为空");
        }
        Float groupSubsidy = entity.getGroupSubsidy();
        if (groupSubsidy == null) {
            groupSubsidy = 0f;
        }
        Float carCost = entity.getCarCost();
        if (carCost == null) {
            return ServerResponse.createByErrorMessage("车费不能为空");
        }
        //门票钱
        float ticketCost = adultNum * adultTicketPrice + childNum * childTicketPrice +
                oldNum * oldTicketPrice +
                otherNum * otherTicketPrice +
                stuNum * stuTicketPrice;
        //计算总花费
        float totalCost = groupSubsidy + carCost + ticketCost;

        //对比前台计算的数据
        Float total = entity.getTotal();
        if (total == null) {
            return ServerResponse.createByErrorMessage("总费用为空");
        }
        if (totalCost != total) {
            return ServerResponse.createByErrorMessage("总费用计算有误");
        }

        //1.判断角色是否是导游
        List<OrgRole> orgRoles = orgRoleMapper.selectByUserUuid(userId);
        if (CollectionUtils.isEmpty(orgRoles)) {
            return ServerResponse.createByErrorMessage("没有找到用户角色");
        }
        for (OrgRole role : orgRoles) {
            if (role.getRoleCode().equals(HConstant.HCLV_GUAI_CONFIRM_YES_ROLE)) {
                entity.setGuideId(userId);
                entity.setCreateUser(userId);
                break;
            }
        }
        String guideId = entity.getGuideId();
        if (StringUtils.isBlank(guideId)) {
            entity.setCreateUser(userId);
        }

        String entityId = FleaStringUtils.getGenerateUUID();
        entity.setId(entityId);
        entity.setLineId(hLine.getId());
        entity.setLineName(hLine.getName());
        entity.setDeptId(currentUserDept.getDeptUuid());
        List<HResourceRelation> files = JSON.parseArray(jsonObject.getString("images"), HResourceRelation.class);
        int row = hSubmitAccountMapper.insertSelective(entity);
        if (row != 1) {
            return ServerResponse.createByErrorMessage("添加失败");
        }
        hResourceRelationService.saveImagesRelation(files, userId, entityId);

        return ServerResponse.createBySuccessMessage("添加成功");
    }

//    private ServerResponse<Float> calculationCost(HSubmitAccount entity) {
//        //计算费用
//        Integer adultNum = entity.getAdultNum();
//        Float adultTicketPrice = entity.getAdultTicketPrice();
//        if (adultNum == null || adultTicketPrice == null) {
//            adultNum = 0;
//            adultTicketPrice = 0f;
//        }
//        Integer childNum = entity.getChildNum();
//        Float childTicketPrice = entity.getChildTicketPrice();
//        if (childNum == null || childTicketPrice == null) {
//            childNum = 0;
//            childTicketPrice = 0f;
//        }
//        Integer oldNum = entity.getOldNum();
//        Float oldTicketPrice = entity.getOldTicketPrice();
//        if (oldNum == null || oldTicketPrice == null) {
//            oldNum = 0;
//            oldTicketPrice = 0f;
//        }
//        Integer otherNum = entity.getOtherNum();
//        Float otherTicketPrice = entity.getOtherTicketPrice();
//        if (otherNum == null || otherTicketPrice == null) {
//            otherNum = 0;
//            otherTicketPrice = 0f;
//        }
//        Float groupMoney = entity.getGroupMoney();
//        if (groupMoney == null) {
//            return ServerResponse.createByErrorMessage("团费不能为空");
//        }
//        Float groupSubsidy = entity.getGroupSubsidy();
//        if (groupSubsidy == null) {
//            groupSubsidy = 0f;
//        }
//        Float carCost = entity.getCarCost();
//        if (carCost == null) {
//            return ServerResponse.createByErrorMessage("车费不能为空");
//        }
//        //门票钱
//        float ticketCost = adultNum * adultTicketPrice + childNum * childTicketPrice + oldNum * oldTicketPrice + otherNum * otherTicketPrice;
//        //计算总花费
//        float totalCost = groupSubsidy + carCost + ticketCost;
//        return ServerResponse.createBySuccess(totalCost);
//    }
}
